let STA = require("STA");

cc.Class({
    extends: cc.Component,

    properties: {
        paintCubes:cc.Node,
        animalsNode:cc.Node,
        tapSound:cc.AudioClip,
        bottomList: cc.Node,
        coinNumber:cc.Node,
        keepBtn:cc.Node,
        successText:cc.Node,
        gift:cc.Node,

        avator:cc.Node,

        rankBlank:cc.Node,
        myRank:cc.Node,
        aRank:cc.Prefab,
        rankContent:cc.Node,

        SuccessRankAvator:cc.Prefab,

        tipFrame:cc.Node,

    },

    onLoad () {
        this.tipFrame.active = false;
        this.rankBlank.active = false;
        this._paintCubes = this.paintCubes.getComponent("paintCubes");

        this.chapterNumber = 15*(STA.bigChapterNumber-1) + STA.smallChapterNumber;
        this.successText.getComponent(cc.Label).string = "第"+ this.chapterNumber +"关";
        this.updateCoinNumberLabel();

        let btns = this.bottomList.children;
        for(let btn of btns){
            this.onBtnClick(btn)
        }

        this.onBtnClick(this.gift);
        this.getRank();
    },

    updateCoinNumberLabel(){
        this.coinNumber.getComponent(cc.Label).string = STA.coinNumber;
    },

    onBtnClick(btn,callback){
        btn.on(cc.Node.EventType.TOUCH_START, (event)=>{
            btn.runAction(cc.sequence(
                cc.scaleTo(0.15,1.1),
                cc.scaleTo(0.15,1),
                cc.callFunc(()=>{
                    if(callback) callback();
                })
            ));
            STA.playAudio(this.tapSound);
        });
    },

    start () {

    },

    cleanAnimal(){
        for(let child of this.animalsNode.children){
            child.active = false;
        }
    },

    chooseAnimal(animalName){  // 获得骨骼，仅仅只有头和尾；身体还需要另外读取
        this.cleanAnimal();
        let theAnimal = this.animalsNode.getChildByName(animalName);
        theAnimal.active = true;
        return theAnimal;
    },

    back(){
        this.cleanAnimal();
        STA.playAudio(this.tapSound);
        cc.director.loadScene("smallChapters");
    },

    // getReward(){
    //     STA.increaseCoin(100);
    //     this.updateCoinNumberLabel();
    // },

    getTip(){
        STA.log("gamePlay - getTip");
        if(this._paintCubes.isTiping){ // 如果正在提示的过程，则无法再点击提示
            STA.log("It's tiping, could not do this action at this moment!");
        }else{
            if(STA.coinNumber < 50){
                // 金币不够，可点击广告或完美过关获得
                this.tipFrame.active = true;
                let tipText = this.tipFrame.getChildByName("tip_text");
                tipText.getComponent(cc.Label).string = "金币不足，可通过 完美过关、分享、求助、奖励、宝箱\n获得金币！";
                let btn = this.tipFrame.getChildByName("blueBtn");
                btn.active = true;
                btn.getChildByName("text").getComponent(cc.Label).string = "好";
                let _this = this;
                btn.on(cc.Node.EventType.TOUCH_START, (event)=>{
                    btn.runAction(cc.sequence(
                        cc.scaleTo(0.15,1.1),
                        cc.scaleTo(0.15,1),
                        cc.callFunc(()=>{
                            _this.tipFrame.active = false;
                            btn.active = false;
                        })
                    ));
                    STA.playAudio(_this.tapSound);
                })
            }else{
                if(STA.result){
                    this._paintCubes.getResult(STA.result);
                }else{
                    this._paintCubes.isTiping = true;
                    let chapterNumber = 15*(STA.bigChapterNumber-1) + STA.smallChapterNumber;
                    cc.loader.loadRes("results/" + chapterNumber,(err,data)=>{
                        if(err) cc.error(err);
                        STA.result = data.json.link;
                        this._paintCubes.getResult(data.json.link);
                    })
                }
                STA.increaseCoin(-50);
                this.updateCoinNumberLabel();
            }
        }
    },

    gamePlayReload(){
        STA.log("gamePlayReload!");
        this.keepBtn.runAction(cc.sequence(
            cc.scaleTo(0.2,1.2),
            cc.scaleTo(0.2,1),
            cc.callFunc(()=>{
                cc.director.loadScene("gamePlay");
            })
        ));
        STA.playAudio(this.tapSound);
    },

    playTapAudio(){
        STA.playAudio(this.tapSound);
    },

    needHelp(){ // 求助 
        STA.share("我在一气呵成里遭遇难题，快来帮一把手！",()=>{
            this.showTipFrame("求助成功，获得25金币！");
            STA.increaseCoin(25);
            this.updateCoinNumberLabel();
        });
    },

    gameShow(){
        STA.share(`我在一气呵成里顺利通过第${this.chapterNumber}关，快来一起攻克难关吧`,()=>{
            this.showTipFrame("炫耀成功，获得50金币！");
            STA.increaseCoin(50);
        });
    },

    showTipFrame(tipTextString){
        let _this = this;
        _this.tipFrame.active = true;
        let tipText = _this.tipFrame.getChildByName("tip_text");
        tipText.getComponent(cc.Label).string = tipTextString;
        let btn = _this.tipFrame.getChildByName("orangeBtn");
        btn.active = true;
        btn.getChildByName("text").getComponent(cc.Label).string = "好";
        btn.on(cc.Node.EventType.TOUCH_START, (event)=>{
            btn.runAction(cc.sequence(
                cc.scaleTo(0.15,1.1),
                cc.scaleTo(0.15,1),
                cc.callFunc(()=>{
                    _this.tipFrame.active = false;
                    btn.active = false;
                })
            ));
            STA.playAudio(_this.tapSound);
        })
    },

    getRank(){

        if(!STA.isQQ){
            return;
        }

        console.log("getRank");
        this.rankList = null;

        // 当前不支持一次同时拉取多个排行榜，需要拉取多次，而且必须等上一个拉取回来后才能拉取另外一个排行榜
        let attr = "score"; 
        let order = 1;     //排序的方法：[ 1: 从大到小(单局)，2: 从小到大(单局)，3: 由大到小(累积)]
        let rankType = 0; //要查询的排行榜类型，0: 好友排行榜
        // 必须配置好周期规则后，才能使用数据上报和排行榜功能
        BK.QQ.getRankListWithoutRoom(attr, order, rankType, (errCode, cmd, data)=>{
            // 返回错误码信息
            if (errCode !== 0) {
                STA.log('获取排行榜数据失败!错误码：' + errCode);
            }else if(data){
                STA.log('成功获取排行榜信息！');
                this.rankList = data.data.ranking_list;
                let overMe = null;
                for(let i=0; i < this.rankList.length; i++) {
                    if(this.rankList[i].selfFlag){
                        let avatorImgUrl = (i==0)? this.rankList[i].url : overMe.url;
                        let avatorLabelString = (i==0)? ("我是第一名") : ("还差"  + (overMe.score  - this.rankList[i].score)+ "关\n超越他！");

                        cc.loader.load({url:avatorImgUrl,type:'jpg'}, (err, texture)=>{
                            if(err) throw err;
                            let sprite = new cc.SpriteFrame(texture);
                            let userImg = this.avator.getChildByName("imgMask").getChildByName("img");
                            userImg.getComponent(cc.Sprite).spriteFrame = sprite;
                            userImg.width = 135;
                            userImg.height = 135;
                        });
                        this.avator.getChildByName("label").getComponent(cc.Label).string = avatorLabelString;
                        break;
                    }else{
                        overMe = this.rankList[i];
                    }
                }
            }
        });
    },

    showVideoAD(){
        if(STA.watchVideoTimes < 20){
            STA.showVideoAD(()=>{
                this.showTipFrame("观看视频，获得100金币！")
                STA.increaseCoin(100);
                STA.addWatchVideoTimes();
                this.updateCoinNumberLabel();
            });
        }else{
            this.showTipFrame("今日视频观看次数已达上限！");
        }
    },

    showRank(event){
        function getTheRankNumImg(obj,num){
            if(num <= 3){
                cc.loader.loadRes("rankNumImg/rank"+num, cc.SpriteFrame,(err,spriteFrame)=>{
                    if(err) STA.log(err);
                    obj.addComponent(cc.Sprite).spriteFrame = spriteFrame;
                });
            }else{
                obj.color = new cc.Color(150,150,150);
                obj.addComponent(cc.Label).string = num;
            }
        }

        this.rankContent.removeAllChildren();
        this.rankBlank.active = true;

        this.aRankHeight = 130;

        this.rankContent.height = this.aRankHeight * this.rankList.length;
        for(let i=0; i < this.rankList.length; i++) {
            let li = this.rankList[i];
            let aRankNode = cc.instantiate(this.aRank);
            aRankNode.active = true;

            getTheRankNumImg(aRankNode.getChildByName("rankNumber"), i+1);

            aRankNode.getChildByName("nick").getComponent(cc.Label).string = li.nick;
            cc.loader.load({url:li.url,type:'jpg'}, (err, texture)=>{
                if(err) throw err;
                let sprite = new cc.SpriteFrame(texture);
                let userImg = aRankNode.getChildByName("userImgMask").getChildByName("userImg");
                userImg.getComponent(cc.Sprite).spriteFrame = sprite;
                userImg.width = 120;
                userImg.height = 120;
            });

            aRankNode.getChildByName("chapterNumber").getComponent(cc.Label).string = "第"+li.score+"关";
            
            aRankNode.y -= this.aRankHeight * (i + 1);
            this.rankContent.addChild(aRankNode);

            if(li.selfFlag){  // 如果是自己，则再加载一次
                let myRankNode = cc.instantiate(this.aRank);
                myRankNode.active = true;

                getTheRankNumImg(myRankNode.getChildByName("rankNumber"), i+1);

                myRankNode.getChildByName("nick").getComponent(cc.Label).string = li.nick;
                cc.loader.load({url:li.url,type:'jpg'}, (err, texture)=>{
                    if(err) throw err;
                    let sprite = new cc.SpriteFrame(texture);
                    let userImg = myRankNode.getChildByName("userImgMask").getChildByName("userImg");
                    userImg.getComponent(cc.Sprite).spriteFrame = sprite;
                    userImg.width = 120;
                    userImg.height = 120;
                });

                myRankNode.getChildByName("chapterNumber").getComponent(cc.Label).string = "第"+li.score+"关";
                
                myRankNode.y = -1/2 * this.aRankHeight;
                this.myRank.addChild(myRankNode);
            }
        }

        event.target.runAction(cc.sequence(
            cc.scaleTo(0.2,1.2),
            cc.scaleTo(0.2,1),
            cc.callFunc(()=>{
                this.isShowRank = true;
            })
        ));
    },
    closeRank(){
        this.rankBlank.active = false;
    }

});
